package com.beiding.controller.error;

import com.beiding.exception.AuthenticationException;
import com.beiding.exception.RegisterException;
import com.beiding.pojo.Error;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestControllerAdvice
public class ErrorAdvice {

    @ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
    @ExceptionHandler(BindException.class)
    public List<Error> bind(BindException e) //表单绑定异常
    {
        List<FieldError> fieldErrors = e.getFieldErrors();
        List<Error> errors = new ArrayList<>(fieldErrors.size());
        fieldErrors.forEach(
                it->errors.add(new Error(it.getField(), it.getDefaultMessage()))
        );
        return errors;
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(RegisterException.class)
    public List<Error> simple(RegisterException e)
    {
        return Collections.singletonList(e.toError());
    }


    @ResponseStatus(HttpStatus.FORBIDDEN)
    public String authentication(AuthenticationException e) {
        return e.getMessage();
    }


}
